﻿using System;

using System.Collections.Generic;

using System.Linq;

using System.Security.Claims;

using System.Threading.Tasks;
using MengRan.Models;
using MengRan.Models.index;
using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;



namespace Server.Controllers

{

    public class AccountController : Controller

    {
        private readonly MyDbContext _dbContext;
        public AccountController (MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>

        /// 登录页面

        /// </summary>

        /// <returns></returns>

        public IActionResult Login()

        {
           

            return View();

        }



        /// <summary>

        /// post 登录请求

        /// </summary>

        /// <returns></returns>

        [HttpPost]

        public async Task<IActionResult> Login(string userName, string password)

        {
            using (_dbContext)
            {
                var list = _dbContext.use.ToList();
                foreach (var item in list)
                {
                    var a = item.username;
                    var b = item.password;




                    if (userName.Equals(a) && password.Equals(b))

                    {

                        var claims = new List<Claim>()
                {

                   new Claim(ClaimTypes.Name,userName),new Claim("password",password)

                };

                        var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));

                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties

                        {

                           // ExpiresUtc = DateTime.UtcNow.AddMinutes(20),

                            IsPersistent = false,

                            AllowRefresh = false

                        });

                        return Redirect("/Home/Index");

                    }

                   

                }
            }
            return Redirect("/Account/Login");
        }



        /// <summary>

        /// 退出登录

        /// </summary>

        /// <returns></returns>

        public async Task<IActionResult> Logout()

        {

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return Redirect("/Login");

        }

    }

}
